package com.wuster.interceptor;

import com.wuster.exception.TokenAuthExpiredException;
import com.wuster.utils.BaseContext;
import com.wuster.utils.JwtUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;


@Slf4j
@Component
public class StudentAuthInterceptor  implements HandlerInterceptor {

    @Autowired
    private JwtUtil jwtUtil;


    /**
     * 权限认证的拦截操作.
     */
    @Override
    public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object object) throws Exception {
        //判断当前拦截到的是Controller的方法还是其他资源
        if (!(object instanceof HandlerMethod)) {
            //当前拦截到的不是动态方法，直接放行
            return true;
        }

        //1、从请求头中获取令牌，为空就返回错误
        String token = httpServletRequest.getHeader("token");
        if (null == token || "".equals(token.trim())) {
            return false;
        }

        //2、校验令牌
        try {
            log.info("=============studentAndUserToken:{}",token);
            Map<String, String> map = jwtUtil.parseToken(token);
            String userId = map.get("userId");
            String userRole = map.get("userRole");
            log.info("当前用户id和角色：{}  {}", userId, userRole);

            BaseContext.setCurrentId(Long.parseLong(userId));

            //1.判断 token 是否过期
            long timeOfUse = System.currentTimeMillis() - Long.parseLong(map.get("expiration"));
            if (timeOfUse <= 0) {
                log.info("studentAndUserToken验证成功");
                return true;
            }
            else {
                throw new TokenAuthExpiredException();
            }

        } catch (Exception ex) {
            //4、不通过，响应401状态码
            httpServletResponse.setStatus(401);
            return false;
        }
    }
}
